package info.batcloud.fanli.admin.controller;

import info.batcloud.fanli.core.service.UserCommissionOrderService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/api/user-commission-order")
public class UserCommissionOrderController {

    @Inject
    private UserCommissionOrderService userCommissionOrderService;

    @GetMapping("/search")
    public Object search(UserCommissionOrderService.SearchParam param) {
        return userCommissionOrderService.search(param);
    }

    @GetMapping("/export")
    public Object export(UserCommissionOrderService.ExportParam param, HttpServletResponse response) throws IOException {
        File file = userCommissionOrderService.exportXls(param);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = URLEncoder.encode("分佣", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + System.currentTimeMillis() + ".xls");
        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            file.delete();
        }
        return null;
    }
}
